package id.co.shuba.spamobile.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.IDatePickerDialog;
import id.co.shuba.spamobile.IDatePickerTarget;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.data.TransactionLogDB;
import id.co.shuba.spamobile.model.ErrorInfo;
import id.co.shuba.spamobile.model.ProspectInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.util.AuditUtil;
import id.co.shuba.spamobile.util.DialogUtil;
import id.co.shuba.spamobile.util.SpinnerUtil;
import id.co.shuba.spamobile.util.Str;
import id.co.shuba.spamobile.util.ValidationUtil;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

public class FormProspectActivity extends SherlockActivity implements
		OnClickListener, IDatePickerDialog, IDatePickerTarget {
	
	private static final int DATE_DIALOG_ID = 212;	
	
	private EditText txtAvgExpense;
	private EditText txtBirthDate;	
	private Spinner spnMaritalStatus;
	private EditText txtSpouseName;
	private Spinner spnProduct;
	private EditText txtNumberOfDependents;
	private EditText txtIdentityNumber;
	private EditText txtIdentityName;
	private EditText txtIdentityAddress;
	private LinearLayout pnlSpouseName;
	private EditText txtPlaceOfBirth;

	private DatabaseHandler _db;
	private ProspectDB _prospectDB;
	private StandardDB _optionDB;	
	private String _prospectID;
	private ProspectInfo _info;
	
	private String defaultOption;
	
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_prospect);	
		setUpLogoutReceiver();
		
		defaultOption = getString(R.string.default_option);
		
		setControls();

		_db = new DatabaseHandler(this);	
		_prospectDB = new ProspectDB(_db);
		_optionDB = new StandardDB(_db);		

		fillSpinner();

		Intent intent = getIntent();
		if (intent.hasExtra("prospectID")) {		
			_prospectID = intent.getStringExtra("prospectID");
			_info = _prospectDB.getDetails(_prospectID);
			if (_info != null && !Str.isNullOrEmpty(_info.getKtpNo())) {				
				loadData(_info);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("Save")
		.setIcon(id.co.shuba.spamobile.R.drawable.ic_action_save)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;    
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle() == "Save") {
			save();
		}
		
	    return super.onOptionsItemSelected(item);
	}
	
	private void fillSpinner() {		
		SpinnerUtil.fillStandard(this, _optionDB, spnMaritalStatus, StandardDB.GROUP_MARITAL_STATUS, defaultOption);
		SpinnerUtil.fillStandard(this, _optionDB, spnProduct, StandardDB.GROUP_PRODUCT, "L", defaultOption);
	}		

	private void setControls() {
		txtAvgExpense = (EditText) findViewById(R.id.txtAvgExpense);
		txtBirthDate = (EditText) findViewById(R.id.txtBirthDate);		
		spnMaritalStatus = (Spinner) findViewById(R.id.spnMaritalStatus);
		txtSpouseName = (EditText) findViewById(R.id.txtSpouseName);
		txtNumberOfDependents = (EditText) findViewById(R.id.txtNumberOfDependents);
		txtIdentityNumber = (EditText) findViewById(R.id.txtIdentityNumber);
		txtIdentityName = (EditText) findViewById(R.id.txtIdentityName);
		txtIdentityAddress = (EditText) findViewById(R.id.txtIdentityAddress);
		spnProduct = (Spinner)findViewById(R.id.spnProduct);	
		pnlSpouseName = (LinearLayout)findViewById(R.id.pnlSpouseName);
		txtPlaceOfBirth = (EditText) findViewById(R.id.txtPlaceOfBirth);
		
		
		spnMaritalStatus.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {				
				setSpouseNameControlVisibility();							
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub			
			}
		});
	}
	
	private void setSpouseNameControlVisibility() {
		String status = SpinnerUtil.optionGetSelectedValue(spnMaritalStatus, defaultOption);
		if (StandardDB.MARITAL_STATUS_MARIED.equals(status)) {
			pnlSpouseName.setVisibility(View.VISIBLE);
		} else {
			txtSpouseName.setText("");
			pnlSpouseName.setVisibility(View.GONE);
		}
	}

	private void loadData(ProspectInfo info) {
		String[] arr = info.getDateOfBirth().split(" ");		
		
		txtAvgExpense.setText(String.valueOf(info.getAvgExpense()));
		txtBirthDate.setText(DialogUtil.changeFormat(arr[0]));
		SpinnerUtil.optionSetSelectedValue(spnMaritalStatus, info.getMaritalStatus());
		txtSpouseName.setText(info.getSpouseName());
		txtNumberOfDependents.setText(String.valueOf(info
				.getJmlTanggungan()));
		txtIdentityNumber.setText(info.getKtpNo());
		txtIdentityName.setText(info.getKtpName());
		txtIdentityAddress.setText(info.getKtpAddress());
		SpinnerUtil.optionSetSelectedValue(spnProduct, info.getProductCode());
		setSpouseNameControlVisibility();
		txtPlaceOfBirth.setText(info.getPlaceOfBirth());
	}
	
	private ProspectInfo getData() {
		UserInfo user = Sessions.getUser(this);
		return getData(user);
	}

	private ProspectInfo getData(UserInfo user) {
		ProspectInfo info = new ProspectInfo();
		info.setId(_prospectID);
		try {
			info.setAvgExpense(Long.parseLong(txtAvgExpense.getText().toString()));
		} catch (Exception e) {		
		}
		
		try {
			info.setJmlTanggungan(Integer.parseInt(txtNumberOfDependents
					.getText().toString()));
		} catch (Exception e) {		
		}
			
		String birthDate = DialogUtil.changeFormat(txtBirthDate.getText().toString());
		if (!Str.isNullOrEmpty(birthDate)) birthDate = birthDate + " 00:00:00";
		
		info.setDateOfBirth(birthDate);
		info.setMaritalStatus(SpinnerUtil.optionGetSelectedValue(spnMaritalStatus, defaultOption));
		info.setSpouseName(txtSpouseName.getText().toString());
		
		info.setKtpNo(txtIdentityNumber.getText().toString());
		info.setKtpName(txtIdentityName.getText().toString());
		info.setKtpAddress(txtIdentityAddress.getText().toString());
		info.setProductCode(SpinnerUtil.optionGetSelectedValue(spnProduct, defaultOption));				
		
		String date = App.getProcessDateTime();
		
		if (_info == null) {
			info.setEntryBy(user.getNip());
			info.setEntryDate(date);	
			info.setPipelineStartTime(date);
		} else {
			info.setEntryBy(_info.getEntryBy());
			info.setEntryDate(_info.getEntryDate());
		}	
		
		info.setUpdateBy(user.getNip());
		info.setUpdateDate(date);
		
		info.setIsUpload("0");
		info.setPlaceOfBirth(txtPlaceOfBirth.getText().toString());
		
		return info;
	}
	

	public void onDateDialogButtonClick(View v) {		
		showDialog(DATE_DIALOG_ID);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return DialogUtil.create(this, txtBirthDate);
		}

		return null;
	}
	
	private List<ErrorInfo> validate(ProspectInfo info) {		
		List<ErrorInfo> errors = new ArrayList<ErrorInfo>();
		//13-01-2014 Remove Avg Expense Mandatory
		/*if (info.getAvgExpense() < 1)
			errors.add(new ErrorInfo(txtAvgExpense, getString(R.string.avg_expense)));*/
		
		if (!DialogUtil.isValidDateTime(info.getDateOfBirth()))
			errors.add(new ErrorInfo(txtBirthDate, getString(R.string.birthdate)));		
		if (info.getMaritalStatus() == null)
			errors.add(new ErrorInfo(spnMaritalStatus, getString(R.string.marital_status)));
		if (StandardDB.MARITAL_STATUS_MARIED.equals(info.getMaritalStatus()) && info.getSpouseName().length() < 3)
			errors.add(new ErrorInfo(txtSpouseName, getString(R.string.spouse_name)));		
		if (info.getProductCode() == null)
			errors.add(new ErrorInfo(spnProduct, getString(R.string.product)));		
		
		/*	10/3/2013
		if (info.getJmlTanggungan() < 1)
			errors.add(new ErrorInfo(txtNumberOfDependents, getString(R.string.number_of_dependents)));
		*/
		
		if (Str.isNullOrEmpty(info.getKtpNo()))
			errors.add(new ErrorInfo(txtIdentityNumber, getString(R.string.identity_number)));
		if (info.getKtpNo().length() > 50)
			errors.add(new ErrorInfo(txtIdentityNumber, getString(R.string.identity_number), "Nomor KTP maksimal 50 karakter"));
		
		if (info.getKtpName().length() < 3)
			errors.add(new ErrorInfo(txtIdentityName, getString(R.string.identity_name)));
		if (info.getKtpName().length() > 50)
			errors.add(new ErrorInfo(txtIdentityName, getString(R.string.identity_name), "Nama KTP maksimal 50 karakter"));
		
		if (info.getKtpAddress().length() < 3)
			errors.add(new ErrorInfo(txtIdentityAddress, getString(R.string.identity_address)));
		if (info.getKtpAddress().length() > 255)
			errors.add(new ErrorInfo(txtIdentityAddress, getString(R.string.identity_address), "Alamat KTP maksimal 255 karakter"));
		
		if (Str.isNullOrEmpty(info.getPlaceOfBirth()))
			errors.add(new ErrorInfo(txtPlaceOfBirth, getString(R.string.place_of_birth)));
		if (info.getPlaceOfBirth().length() > 50)
			errors.add(new ErrorInfo(txtPlaceOfBirth, getString(R.string.place_of_birth), "Tempat lahir maksimal 50 karakter"));
		
		return errors;
	}	

	private void save() {
		try {
			UserInfo user = Sessions.getUser(this);
			ProspectInfo info = getData();			
			
			List<ErrorInfo> errors = validate(info);
			
			if (errors.size() == 0) {					
				_prospectDB.updateDetails(info);									
				
				TransactionLogDB trans = new TransactionLogDB(_db);	
				trans.add(user.getNip(), "UPDATE", "UPDATE PIPELINE ID="+info.getProspectID());
				
				setResult(Activity.RESULT_OK);
				finish();
			} else {
				ValidationUtil.showValidationDialog(this, errors, this);
			}
			
		} catch (Exception e) {				
			e.printStackTrace();
		}
		
	}

	public void onClick(View v) {
		save();				
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();			
	}

	public void show(EditText txt) {
		showDialog(DATE_DIALOG_ID);
	}

	public EditText getEditText() {		
		return txtBirthDate;
	}
	
	@Override
	public void onBackPressed() {
		ProspectInfo info = getData();
		boolean isChanged = false;
		try {
			isChanged = AuditUtil.isFormChanged(ProspectInfo.class, _info, info, defaultOption);
		} catch (Exception e) {		
			e.printStackTrace();
		}	
		
		if (!isChanged) {
			finish();
			return;
		}		
		
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage(R.string.save_changes)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {    
            	dialog.dismiss();
                save();    
            }
        })
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                
                finish();    
            }
        })
        .show();       
	}
}
